{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "UP2Th8B0LLey"
   },
   "source": [
    "# Practical 1: Introduction to Python (1)\n",
    "\n",
    "Upon completion of this session you should be able to:\n",
    "\n",
    "   - understand the software and resources available for this unit\n",
    "   - know how to use ipython notebook\n",
    "   - understand the basic syntax of Python, its data structure and control statements\n",
    "   - create basic Python programs\n",
    "\n",
    "---\n",
    "- Materials in this module include resources collected from various open-source online repositories.\n",
    "- Jupyter source file can be downloaded from clouddeakin SIT384 > weekly resources or https://github.com/gaoshangdeakin/SIT384-Jupyter\n",
    "- If you found any issue/bug for this document, please submit an issue at [https://github.com/gaoshangdeakin/SIT384/issues](https://github.com/gaoshangdeakin/SIT384/issues)\n",
    "\n",
    "\n",
    "---\n",
    "\n",
    "\n",
    "## Background\n",
    "\n",
    "### Python\n",
    "\n",
    "   - Python is a popular programming language. It can be used for data analytics, mathematics and server-side web scripting, etc.\n",
    "   - Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).\n",
    "   - Python has a simple syntax and efficient high-level data structures that allows developers to write programs with fewer lines.\n",
    "   - Python runs on an interpreter system. The most recent verson is Python 3, which we will be using in this unit.\n",
    "   - Python can be treated in a procedural way, an object-orientated way or a functional way.\n",
    "\n",
    "The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from [the Python Web site](https://www.python.org/), and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation. You can download Python from [the Python Software Foundation website](https://www.python.org/downloads/). In this unit, we recommend you use a Python distribution called \"[Anaconda](https://www.anaconda.com/distribution/)\", which is the easiest way to performing Python/R data science and machine learning on Linux, Windows, and Mac OS X, available from Anaconda Distribution.\n",
    "\n",
    "Try to download [Anaconda python (3.7 version)](https://www.anaconda.com/distribution/), and get familiar with the included tools and packages. \n",
    "\n",
    "We can use the integrated editor \"Spyder\" to code our first Python program in this prac. Open Spyder editor in Anaconda, type a simple line such as \n",
    "\n",
    "print (\"hello world\")\n",
    "\n",
    "as shown in the figure, and you just create your first Python program! \n",
    "\n",
    "<img src=\"./images/p01/create-python-program-using-spyder.jpg\" width=\"60%\" and height=\"60%\">\n",
    "\n",
    "If you just have Python (from www.python.org) installed instead of an IDE such as Anaconda, you can save the line in a file named helloworld.py, and run as a command line:\n",
    "\n",
    "C:\\your python installation path> python helloworld.py\n",
    "\n",
    "Or go to the Python installation folder, type python, you enter the python command line. You input Python code (e.g. print (\"hello world\")) after the prompt. Whenever you are done, you can simply type exit() to quit the python command line interface.\n",
    "\n",
    "We can also run *Python* code under  **IPython notebook** (Jupyter notebook in Anaconda). For the latter, you have two options to use it:\n",
    "\n",
    "1. After installing the [Anaconda](https://www.anaconda.com/distribution/),  run jupyter notebook locally; **OR**\n",
    "1. Use one cloud data science platform such as:\n",
    "    - [Google Colab](https://colab.research.google.com): Google Colab is recommended for this unit if you don't have Anaconda available at hand. \n",
    "    - [IBM Cloud](https://www.ibm.com/cloud)\n",
    "    - [DataBricks](https://community.cloud.databricks.com)\n",
    "\n",
    "\n",
    "In IPython notebook, you will be able to execute and modify your *Python* code more efficiently. If you are using Google Colab for SIT384 practicals, you can ignore the Part 1 of this prac, and start with Part 2.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "V0vSWcazLLe3"
   },
   "source": [
    "## Content\n",
    "\n",
    "### Part 1 Create your own IPython notebook\n",
    "\n",
    "1.1 [Start a notebook server](#cell_start)\n",
    "\n",
    "1.2 [A tour of IPython notebook](#cell_tour)\n",
    "\n",
    "1.3 [IPython notebook infterface](#cell_interface)\n",
    "\n",
    "1.4 [Open and close notebooks](#cell_close)\n",
    "\n",
    "### Part 2 Python syntax\n",
    "\n",
    "2.1 [Creating variables](#variable)\n",
    "\n",
    "2.2 [Python numbers, casting and strings](#number_casting_string)\n",
    "\n",
    "\n",
    "### Part 3  Python operators\n",
    "\n",
    "### Part 4  Python collections\n",
    "4.1 [list](#list)\n",
    "\n",
    "4.2 [tuple](#tuple)\n",
    "\n",
    "4.3 [set](#set)\n",
    "\n",
    "4.4 [dictionary](#dictionary)\n",
    "\n",
    "\n",
    "### Part 5 Python control statements\n",
    "\n",
    "5.1 [conditional statement](#onditional)\n",
    "\n",
    "5.2 [loop statements](#loop)\n",
    "\n",
    "### Tasks\n",
    "\n",
    "### Summary\n",
    "\n",
    "### Reference\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "DAeickflLLe7"
   },
   "source": [
    "## Part 1. Create your own IPython notebook\n",
    "\n",
    "If you are using Google Colab for SIT384 lab practicals, you can ignore this Part 1, and start with Part 2.\n",
    "\n",
    "This section will show you how to start an IPython notebook. It guides you through the process of creating your own notebook. It provides you details on the notebook interface and shows you how to navigate and manipulate its components. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "C6uxTijTLLe_"
   },
   "source": [
    "<a id = \"cell_start\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "JO2tcWluLLfB"
   },
   "source": [
    "     \n",
    "### 1. 1 Start  a  notebook server\n",
    "\n",
    "Created a folder for this section, e.g. **p01** under **C:/tmp/units/sit384**, download the file  **SIT384P01A-Python.ipynb** notebook, and saved it under **C:/tmp/units/sit384/p01**. \n",
    "\n",
    "From \"start\" (if using Windows platform), locate and run \"Anaconda Prompt (anaconda3)\". You will open an \"Anaconda prompt\" command line window with \"(base) c:\\>\" which is the base directory of your Anaconda installation. To change the file open path, first go to your target file folder (e.g. C:/tmp/units/sit384) using \"cd c:\\tmp\\units\\sit384\", then type in \"jupyter notebook\", you will open an ipython notebook window with the current path C:/tmp/units/sit384 as your \"root\" path. In the ipython notebook window, you can navigate to the target notebook file. \n",
    "\n",
    "\n",
    "If you are using [Google Colab](https://colab.research.google.com), you can upload this notebook to Google Colab and run it from there. If any difficulty, please ask your tutor, or check the CloudDeakin discussions.\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "yWJLYqESLLfH"
   },
   "source": [
    "You can see the message in the terminal windows as follows:\n",
    "\n",
    "\n",
    "<img src=\"./images/p01/open-jupyter-notebook.jpg\">\n",
    "\n",
    "This will open a new browser window(or a new tab in your browser window). In the browser, there is an **dashboard**  page which shows you all the folders and files under your **sit384** folder.\n",
    "\n",
    "\n",
    "<img src=\"./images/p01/jupyter-notebook-file-navigatioin.jpg\">\n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "HTSWM3swLLfJ"
   },
   "source": [
    "<a id = \"cell_tour\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "Slhkb9iqLLfM"
   },
   "source": [
    " \n",
    " ### 1.2  A tour of iPython notebook \n",
    " \n",
    " ###  Create a new ipython notebook (.ipynb)\n",
    " \n",
    " \n",
    "If you want to create a new notebook, go to the menu bar and select **File -> New Notebook -> Python 3**\n",
    "\n",
    "By default, the new notebook is named **Untitled**. To give your notebook a meaningful name, click on the notebook name and rename it. We would like to call our new notebook **hello.ipynb**. Therefore, key in the name **hello**. \n",
    "\n",
    "<img src=\"./images/p01/emptyNotebook.jpg\" width=\"60%\" and height=\"60%\">\n",
    "\n",
    "\n",
    "\n",
    "###  Run script in code cells\n",
    "\n",
    "After a new notebook is created, there is an empty box in the notebook, called a **cell**. If you double click on the cell, you enter the **edit** mode of the notebook. Now we can  enter the following code in the cell"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "raw",
    "id": "KjqBdqFeLLfO"
   },
   "source": [
    "text = \"Hello World\"\n",
    "print(text)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "NYDnH3V1LLfR"
   },
   "source": [
    "After this,  press **CTRL + ENTER**, and execute the cell. The result will be shown after the cell. \n",
    "\n",
    "\n",
    "\n",
    "<img src=\"./images/p01/hello-world.jpg\" width=\"60%\" and height=\"60%\">\n",
    "\n",
    "\n",
    "After a cell is executed, the notebook is switched to  the **Commmand** mode. In this mode,  you can manipulte the notebook and its commponent. Alternatively, you can  use **ESC** key to switch from **Edit** mode to **Command** mode without executing code (note: seemed it might not work on win10). \n",
    "\n",
    "To modify the code you  entered in the cell, **double click** the cell again and modify its content.  For example, try to change the first line of previouse cell into the following code:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "raw",
    "id": "TJQbOFqJLLfU"
   },
   "source": [
    "text = \"Good morning World!\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "YhgTgof0LLfX"
   },
   "source": [
    "Afterwards,  press **CTRL + ENTER**, and the new output is displayed. \n",
    "\n",
    "As you can see, you are switching bewteen two  modes,  **Command** and  **Edit**,  when  editing a notebook. We will in  later section look into these two operation modes closely. Now practise  switching between the two modes until you are comfortable with them. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "N3q3nZrQLLfY"
   },
   "source": [
    "###  Add  new  cells\n",
    "\n",
    "To add a new cell to a notebook, you have to ensure the notebook is in **Command** mode. If not, refer to previous section to switch to **Command** mode. \n",
    "\n",
    "\n",
    "To add cell below the currrent cell, go to menubar and click **Insert-> Insert Cell Below**. Alternatively, you can use shortcut i.e.  pressing **b** (or **a** to create a cell above).\n",
    "\n",
    "\n",
    "###  Add markdown cells\n",
    "\n",
    "By default, a code cell is created when adding a new cell. However, IPython notebook also uses a **Markdown** cell for   normal text. We use markdown cell to display text in a specific format and to provide structure for a notebook.  \n",
    "\n",
    "Try to copy the text in the cell below and paste it into your new  notebook. Then from toolbar(**Cell->Cell Type**), change  cell type from **Code** to **Markdown**. \n",
    "\n",
    "Please note in the following cell,  there is a space between the leading **-, #, 0** and the text that follows. "
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {
    "colab_type": "raw",
    "id": "yE7_3iNPLLfa"
   },
   "source": [
    "## Heading 2\n",
    "Normal text here!\n",
    "\n",
    "### Heading 3\n",
    "ordered list here\n",
    "\n",
    "1. Fruits\n",
    "  1. Banana\n",
    "  1. Grapes\n",
    "1. Veggies\n",
    "  1. Tomato\n",
    "  1. Broccoli\n",
    " \n",
    "Unordered list here\n",
    "- Fruits\n",
    "     - Banana\n",
    "     - Grapes\n",
    "- Veggies\n",
    "     - Tomato\n",
    "     - Broccoli"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "collapsed": true,
    "id": "slcY8TkgLLfc"
   },
   "source": [
    "Now execute the cell by press **CTRL+ ENTER**. You will see headings and ordered/unordered list.   \n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "FNzxurYjLLfj"
   },
   "source": [
    "<a id = \"cell_interface\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "R0RQeVQlLLfn"
   },
   "source": [
    " \n",
    "### 1.3  IPython notebook interface\n",
    "\n",
    "Now you have created your first notebook, let us have a close look at the user interface of IPython notebook.\n",
    "\n",
    "\n",
    "\n",
    "### Notebook component\n",
    "When you create a new notebook document, you will be presented with the notebook name, a menu bar, a toolbar and an empty code cell.\n",
    "\n",
    "We can see the following components in a notebook:\n",
    "\n",
    "- **Title bar** is at the top of the page and  contains the name of the notebook. Clicking on the notebook name brings up a dialog which allows you to rename it.  Please renaming your notebook name from “Untitled0” to “hello”. This change the file name from **Untitled0.ipynb**  to  **hello.ipynb**.\n",
    "\n",
    "- **Menu bar** presents different options that can be used to manipulate the way the notebook functions.\n",
    "\n",
    "- **Toolbar** gives a quick way of performing the most-used operations within the notebook.\n",
    "\n",
    "- An empty computational cell is  show in a new notebook where you can key in your code.\n",
    "\n",
    "The notebook has two  modes of operatiopn:\n",
    "\n",
    "- **Edit**: In this mode, a single cell comes into focus and you can enter text or execute code.  You activate the **Edit mode** by **clicking on a cell** or **selecting a cell and then pressing Enter key**.\n",
    "\n",
    "- **Command**: In this mode, you can perform tasks that is related to the whole notebook structure. For example, you can move, copy, cut and paste cells. A series of keyboard shortcuts are also available to enable you to performa  these tasks more effiencient. One easiest way of activating the command mode by  pressing the **Esc** key to exit editing mode. \n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "### Get help and interrupting\n",
    "\n",
    "\n",
    "To get help on the use of different cammands, shortcuts, you can go to the **Help** menu, which provides links to relevant documentation.\n",
    "\n",
    "It is also easy to get help on any objects(including functions and methods). For example, to access help on the sum() function, enter the followsing line in a cell:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "raw",
    "id": "TGoAeYhYLLfp"
   },
   "source": [
    "sum?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "tbgcq5bXLLfu"
   },
   "source": [
    "The other improtant thing to know is how to interrupt a compuation. This can be done through the menu **Kernel->Interrupt** or **Kernel->Restart**, depending on what works on the situation. We will have chance to try this in later session. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "C0Ra6R3PLLfw"
   },
   "source": [
    "\n",
    "### Notebook cell types\n",
    "\n",
    "\n",
    "There are basically three types of cells in a IPython notebook: Code Cells, Markdown Cells, Raw Cells.\n",
    "\n",
    "\n",
    "**Code cells** : Code cell can be used to enter code and will be executed by Python interpreter. Although we will not use other language in this unit, it is good to know that Jupyter Notebooks  also support JavaScript,  HTML, and Bash commands.\n",
    "\n",
    "*** Markdown cells***: You have created markdown cell in the previouse section. Markdown Cells are the easiest way to write and format text. It is also give structure to the notebook. Markdown language is used in this type of cell. Follow this link https://daringfireball.net/projects/markdown/basics  for the basics of the syntax.  \n",
    "\n",
    "This is a  Markdown Cells example notebook sourced from : https://ipython.org/ipython-doc/3/notebook/notebook.html\n",
    "This markdown cheat sheet can also be good reference to the main markdowns you might need to use in our pracs http://nestacms.com/docs/creating-content/markdown-cheat-sheet\n",
    "\n",
    "\n",
    "**Raw cells** : Raw cells, unlike all other Jupyter Notebook cells, have no input-output distinction. This means that raw Cells cannot be rendered into anything other than what they already are. They are mainly used to create examples.\n",
    "\n",
    "\n",
    "As you have seen, you can use the toolbar to choose between different cell types. In addition, shortcut **M** and **Y** can be used to quickly change a cell to Code cell or Markdown cell under Command mode. \n",
    "\n",
    "\n",
    "### Operation modes of IPytho notebook\n",
    "\n",
    "**Edit mode**\n",
    "\n",
    "\n",
    "\n",
    "The Edit mode is used to enter text in cells and to execute code. As you have seen, after typing some code in the notebook and pressing **CTRL+Enter**, the notebook executes the cell and diplays  output. The other two shortcuts used to run  code in a cell are **Shift +Enter** and **Alt + Enter**. \n",
    "\n",
    "These three ways to run the the code in a cells are summarized as follows:\n",
    "\n",
    "\n",
    "- Pressing Shift + Enter: This runs the cell and select the next cell (A new cell is created if at the end of the notebook). This is the most usual way to execute a cell.\n",
    "\n",
    "- Pressing Ctrl + Enter: This runs the cell and keep the same cell selected. \n",
    "\n",
    "- Pressing Alt + Enter: This runs the cell and insert a new cell below it. \n",
    "\n",
    "\n",
    "**Command mode**\n",
    "\n",
    "In Command mode, you can edit the notebook as a whole, but not type into individual cells.\n",
    "\n",
    "You can use keyboard shortcut in this mode to perform the notebook and cell actions effeciently. For example, if you are in command mode and press **c**, you will copy the current cell. \n",
    "\n",
    "\n",
    "\n",
    " There are a large amount of shortcuts avaialbe in the command mode. However, you do not have to remember all of them, since most actions in the command mode are available in the menu. \n",
    " \n",
    " Here is a list of the most useful shortcuts. They are arrganged by the \n",
    "  order we recommend you learn so that you can edit the cells effienctly.\n",
    "\n",
    "\n",
    "1. Basic navigation: \n",
    "\n",
    "   - Enter: switch to Edit mode\n",
    "   \n",
    "   - Esc: switch to Command mode\n",
    "   \n",
    "   - Shift+enter: Eexecute a cell\n",
    "   \n",
    "   - Up, down: Move to the cell above or below\n",
    "\n",
    "2. Cell types: \n",
    "  - y: switch to code cell\n",
    "  - m: switch to markdown cell \n",
    "\n",
    "3. Cell creation: \n",
    "    - a: insert new sell above\n",
    "    - b: insert new cell  below\n",
    "\n",
    "4. Cell deleting:\n",
    "    - press D twice.\n",
    "\n",
    "Note that one of the most common (and frustrating) mistakes when using the\n",
    "notebook is to type something in the wrong mode. Remember to use **Esc**\n",
    "to switch to the Command mode and **Enter** to switch to the Edit mode.\n",
    "Also, remember that **clicking** on a cell automatically places it in the Edit\n",
    "mode, so it will be necessary to press **Esc** to go to the Command mode.\n",
    "\n",
    " \n",
    "For a complete list of shortcut in **Command** mode, go to menu bar **Help->Keyboardshorcut**. Feel free to explore the other shortcuts. \n",
    " \n",
    "  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "M2sk2y0ILLfy"
   },
   "source": [
    "<a id = \"cell_close\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "W0JXgsqELLf0"
   },
   "source": [
    " \n",
    " ### 1.4 open and close notebooks\n",
    " \n",
    " You can open multiple notebooks in a browser windows. Simply go to menubar and choose **File->open...**, and select one **.ipynb** file. The second notebook will be opened in a seperated tab. \n",
    " \n",
    " When you finish your work, you will need to close your notebooks and shutdown the IPython notebook server. Instead of simply close all the tabs in the browser, you need to shutdown each notebook first. To do this, swich to   the **Home** tab(**Dashboard page**) and  **Running** section(see below).  Click on **Shutdown** button to close each notebook. In case  **Dashboard** page is not open,  click on the **Jupyter** icon to reopen it. \n",
    " \n",
    "\n",
    " <img src=\"./images/p01/running-jupyter-notebooks.jpg\">\n",
    " \n",
    " After each notebook is shutdown, it is time to showdown the IPython notebook server. To do this, go to the terminal window and press **CTRL + C**, and then enter **Y**. After the notebook server is shut down,  the terminal window is ready for you to enter any new command. \n",
    " "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "WKEEelJeLLf2"
   },
   "source": [
    "\n",
    "## Part 2  Python syntax\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Python has some some similarities to the English language. It uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses. Also Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\" This is a multiple\n",
    "docstring. It is also a comment.\n",
    "Python use triple quotes at the beginning and end of the docstring \"\"\"\n",
    "#This is a comment.\n",
    "if 2 > 1:\n",
    "  print(\"Two is greater than 1.\") "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "THnW6RPgLLf6"
   },
   "source": [
    "<a id = \"variable\"></a>\n",
    "### 2.1 Creating variables\n",
    "\n",
    "Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Variables do not need to be declared with any particular type and can even change type after they have been set. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "CG-9AQrmLLf7"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x value is:10\n"
     ]
    }
   ],
   "source": [
    "x=\"hello\" # x is of type str\n",
    "x=10 # x is now of type int\n",
    "print(\"x value is:\" + str(x)) # use '+' to combine text and variable which should be of string type "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "ZPKAMR6WLLgI"
   },
   "source": [
    "A variable can have a short name (like x and y) or a more descriptive name (studentID, price, total_volume). It must start with a letter or the underscore character; It cannot start with a number; It can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) and it is case sensitive. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"number_casting_string\"></a>\n",
    "### 2.2 Python numbers, casting and strings"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are three numeric types in Python: int, float and complex. To verify the type of any object, use type() function. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting in python is done using constructor functions:\n",
    "\n",
    "   - int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)\n",
    "   - float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)\n",
    "   - str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "5ZsarfIpLLgO"
   },
   "outputs": [],
   "source": [
    "x=float(1) # x is 1.0 now\n",
    "y=str(10.2) # y is '10.2' now\n",
    "z=int(2.5) # z is 2 now "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "cm9IgbLyLLgU"
   },
   "source": [
    "String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "colab": {},
    "colab_type": "code",
    "id": "zilCIz-GLLga"
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "h\n",
      "llo\n",
      "11\n",
      "hello world\n",
      "HELLO WORLD\n"
     ]
    }
   ],
   "source": [
    "x=\"hello world\"\n",
    "print(x[0]) # print 'h'\n",
    "print(x[2:5]) # print a substring from postion 2 to 5 (not included) 'llo'\n",
    "print(len(x)) # print the length of string x\n",
    "print (x.lower()) # print the string in lower case\n",
    "print(x.upper()) # print the string in upper case"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "colab_type": "text",
    "id": "zshg7IvZLLgp"
   },
   "source": [
    "<a id = \"operator\"></a>\n",
    "## Part 3 Python operators"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are arithmetic, assignment, comparison, logical, identity, membership bitwise operators:\n",
    "\n",
    " <img src=\"./images/p01/arithmetic.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/assignment.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/comparison.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/logical.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/identity.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/membership.jpg\" width=\"30%\" and height=\"30%\">\n",
    "\n",
    " <img src=\"./images/p01/bitwise.jpg\" width=\"40%\" and height=\"40%\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"collection\"></a>\n",
    "\n",
    "## Part 4 Python collections\n",
    "\n",
    "There are four collection data types in Python. When choosing a collection type, it is important to understand the properties of that type.\n",
    "\n",
    "   - List is a collection which is ordered and changeable. Allows duplicate members.\n",
    "   - Tuple is a collection which is ordered and unchangeable. Allows duplicate members.\n",
    "   - Set is a collection which is unordered and unindexed. No duplicate members.\n",
    "   - Dictionary is a collection which is unordered, changeable and indexed. No duplicate members.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"list\"></a>\n",
    "\n",
    "#### 4.1 List"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "apple\n"
     ]
    }
   ],
   "source": [
    "#create a list. In Python lists are written with square brackets.\n",
    "mylist = [\"apple\", \"banana\", \"cherry\"]\n",
    "\n",
    "#print the first item of the list\n",
    "print(mylist[0])\n",
    "\n",
    "#change the first item\n",
    "mylist[0] = \"blueberry\" "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"tuple\"></a>\n",
    "\n",
    "#### 4.2 Tuple"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create a tuple. In Python tuples are written with round brackets.\n",
    "mytuple = (\"apple\", \"banana\", \"cherry\") # or use: mytuple = tuple((\"apple\", \"banana\", \"cherry\"))\n",
    "\n",
    "#print the first item of the tuple\n",
    "print(mytuple[0])\n",
    "\n",
    "#Once a tuple is created, you cannot change its values. They are unchangeable.\n",
    "mytuple[0] = \"blueberry\" # nothing will happen to the tuple\n",
    "\n",
    "#iterate through the items of a tuple\n",
    "for x in mytuple:\n",
    "  print(x)\n",
    "\n",
    "#check if \"apple\" is present in the tuple:\n",
    "if \"apple\" in mytuple:\n",
    "  print(\"Yes, 'apple' is in mytuple\")\n",
    "\n",
    "#print the length of a tuple\n",
    "print(len(mytuple))\n",
    "\n",
    "#delete a tuple\n",
    "del mytuple\n",
    "print(mytuple) #this will raise an error because the tuple no longer exists\n",
    "#you can also use count() to return the number of times a specified value occurs in a tutple; index() to search for a specified value and return the position if found"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"set\"></a>\n",
    "\n",
    "#### 4.3 Set"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create a set. In Python sets are written with curly brackets.\n",
    "myset = {\"apple\", \"banana\", \"cherry\"} # or use: myset = set((\"apple\", \"banana\", \"cherry\"))\n",
    "\n",
    "#iterate through the items of a set\n",
    "for x in myset:\n",
    "  print(x)\n",
    "\n",
    "#check if \"apple\" is present in the set:\n",
    "if \"apple\" in myset:\n",
    "  print(\"Yes, 'apple' is in myset\")\n",
    "print(\"apple\" in myset) #or use this way\n",
    "\n",
    "#Once a set is created, you cannot change its items, but you can add new items.\n",
    "myset.add(\"blueberry\") #use add() to add a new item\n",
    "myset.update([\"blueberry\", \"strawberry\", \"grapes\"]) #user update() to add multiple items\n",
    "\n",
    "myset.remove(\"blueberry\") #use remove() to remove an item. Error raised if the item doesnot exist.\n",
    "myset.discard(\"blueberry\") #use discard() to remove an item. NO error raised if the item doesnot exist.\n",
    "#print the length of a set\n",
    "print(len(myset))\n",
    "\n",
    "#empty a set\n",
    "myset.clear()\n",
    "#delete a set completely\n",
    "del myset\n",
    "\n",
    "print (myset) #this will raise an error because the set no longer exists\n",
    "#There are many built-in methods you can use on sets. E.g. You can use copy() to return a copy of the set; difference() to return a set containing the difference between two or more sets; union() to return a set containing the union of sets;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"dictionary\"></a>\n",
    "\n",
    "#### 4.4 Dictionary"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#create a dictionary. In Python dictionaries are written with curly brackets, and they have keys and values.\n",
    "mydict = {\n",
    "   \"name\": \"John\",\n",
    "   \"id\": 12345,\n",
    "   \"course\": \"s326\"\n",
    "}\n",
    "#you can also use dict() constructor. eg.\n",
    "#mydict = dict(name=\"John\", id=12345, course=\"s326\")\n",
    "\n",
    "#get the value of \"name\" key\n",
    "x = mydict[\"name\"]\n",
    "#you can also use get()\n",
    "x = mydict.get(\"name\")\n",
    "#change a key's value\n",
    "mydict[\"course\"]= \"s334\"\n",
    "\n",
    "#iterate through a dictionary\n",
    "#print all key names\n",
    "for x in mydict:\n",
    "  print(x)\n",
    "\n",
    "#print all values\n",
    "for x in mydict:\n",
    "  print(mydict[x])\n",
    "\n",
    "#you can also use values() function to return values\n",
    "for x in mydict.values():\n",
    "   print(x)\n",
    "\n",
    "#Loop through both keys and values, by using the items() function:\n",
    "for x, y in mydict.items():\n",
    "   print(x, y)\n",
    "\n",
    "#check if \"name\" is present in the dictionary:\n",
    "if \"name\" in mydict:\n",
    "  print(\"Yes, 'name' is in mydict\")\n",
    "\n",
    "\n",
    "#Once a dictionary is created, you can add new items using new index key and value.\n",
    "mydict[\"birthday\"] = \"March 1st, 2000\"\n",
    "#user pop() to remove an item with specified key\n",
    "mydict.pop(\"name\")\n",
    "#print the length of a dictionary\n",
    "print(len(mydict))\n",
    "\n",
    "#delete a dictionary item with specified key\n",
    "del mydict[\"id\"]\n",
    "#delete a dictionary completely\n",
    "del mydict\n",
    "print(mydict) #this will raise an error because the dict no longer exists\n",
    "\n",
    "#There are many built-in methods you can use on dictionaries. E.g. You can use copy() to return a copy of the dict; fromkeys() to return a dictionary with the specified keys and values; clear() to remove all items from the dictionary;"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"control\"></a>\n",
    "\n",
    "## Part 5 Python control statements"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Like other programming languages, Python has conditional and loop statements:\n",
    "\n",
    "   - if ... elif and else\n",
    "   - while and for loop\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"conditional\"></a>\n",
    "\n",
    "#### 5.1 Conditional statement\n",
    "\n",
    "Python supports the usual logical conditions from mathematics. Please note: Python relies on indentation, using whitespace, to define scope in the code. Other programming languages often use curly-brackets for this purpose. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = 100\n",
    "b = 99\n",
    "if b > a:\n",
    "   print(\"b is greater than a\")\n",
    "elif a == b:\n",
    "   print(\"a and b are equal\")\n",
    "else:\n",
    "   print(\"a is greater than b\")\n",
    "\n",
    "#you can also use if ...else\n",
    "if b > a:\n",
    "   print(\"b is greater than a\")\n",
    "else:\n",
    "   print(\"b is not greater than a\")\n",
    "\n",
    "#if only one statement to execute, use short hand if else if a > b: print(\"a is greater than b\")\n",
    "print(\"A\") if a > b else print(\"B\") "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a id = \"loop\"></a>\n",
    "\n",
    "#### 5.2 Loop statements\n",
    "\n",
    "Python has two primitive loop statements: while and for."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#print i as long as it is less than 6\n",
    "i = 1\n",
    "while i < 6:\n",
    "   print(i)\n",
    "   i += 1\n",
    "\n",
    "#use break to stop the loop if a condition is true\n",
    "#exit the loop when i is 3:\n",
    "i = 1\n",
    "while i < 6:\n",
    "  print(i)\n",
    "  if i == 3:\n",
    "      break\n",
    "  i += 1\n",
    "\n",
    "#use continue to stop the current iteration and continue with the next\n",
    "#continue to the next iteration if i is 3\n",
    "i = 1\n",
    "while i < 6:\n",
    "  print(i)\n",
    "  if i == 3:\n",
    "    i += 1\n",
    "    continue\n",
    "  i += 1 "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). As you've seen in previous examples, for statement is less like the for keyword in other programming language, and works more like an iterator method as found in other object-orientated programming languages. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#exit the loop when x is \"banana\" using break\n",
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "for x in fruits:\n",
    "  print(x)\n",
    "  if x == \"banana\":\n",
    "     break\n",
    "\n",
    "#stop current iteration and continue with the next using continue\n",
    "for x in fruits:\n",
    "  if x == \"banana\":\n",
    "     continue\n",
    "  print(x)\n",
    "\n",
    "#To loop through a set of code a specified number of times,\n",
    "#we can use the range() function. It starts from 0, and increments by 1 by default. for x in range(6):\n",
    "  print(x)\n",
    "\n",
    "#range(2,6) starts from 2 to 6 (but NOT including 6)\n",
    "for x in range(2, 6):\n",
    "   print(x)\n",
    "\n",
    "#create a nested loop\n",
    "adj = [\"red\", \"big\", \"tasty\"]\n",
    "fruits = [\"apple\", \"banana\", \"cherry\"]\n",
    "\n",
    "for x in adj:\n",
    "  for y in fruits:\n",
    "    print(x, y)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "More Python information and examples can be found at [Python examples](https://www.w3schools.com/python/python_examples.asp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Tasks\n",
    "\n",
    "Try the provided examples and get yourself familiar with Python syntax before attempting portolio tasks.\n",
    "\n",
    "Please show your attempt to your tutor before you leave the lab, or email your files to your coordinator if you are a cloud student.\n",
    "\n",
    "## Summary\n",
    "\n",
    "In this session we have covered\n",
    "\n",
    "   - Ipython notebook\n",
    "   - Python syntax, such as variables, collection structures and most of the commonly used control statements;\n",
    "   - Coding your first Python program\n",
    "\n",
    "## Reference:\n",
    "\n",
    "   - Python tutorial, available at [w3schools](https://www.w3schools.com/python/default.asp), accessed 8th of March, 2020.\n",
    "   - Python Software Foundation, available at [www.python.org](https://www.python.org/), accessed 8th of March, 2020.\n",
    "   - Anaconda website, available at [www.anaconda.com](https://www.anaconda.com/), accessed 8th of March, 2020.\n"
   ]
  }
 ],
 "metadata": {
  "colab": {
   "collapsed_sections": [],
   "name": "SIT742P01A-Python.ipynb",
   "provenance": [],
   "version": "0.3.2"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
